<?php

namespace common\model\sell66;

use common\db\Sell66;
use common\model\sell66\UserBalanceLog;

class UserBalance extends Sell66 {
	// 设置当前模型对应的完整数据表名称
	protected $table = 'user_balance';
	protected $pk = 'user_balance_id';
	const MIN_WITHDRAW_MONEY = 10;
	/**
	 * 创建用户钱包
	 * 
	 * @param unknown $userId        	
	 * @return Ambigous <NULL, multitype:, multitype:\think\mixed multitype:multitype: multitype: NULL Ambigous <\think\mixed, NULL, multitype:, mixed, unknown, string> >|NULL|Ambigous <multitype:, multitype:\think\mixed multitype:multitype: multitype: NULL Ambigous <\think\mixed, NULL, multitype:, mixed, unknown, string> >
	 */
	public static function createUserBalance($userId) {
		$userBalance = self::getBalanceByUseId ( $userId );
		if ($userBalance) {
			return $userBalance->toArray ();
		}
		$userBalanceModel = new self ();
		$userBalanceModel->user_id = $userId;
		$userBalanceModel->balance = 0;
		$userBalanceModel->transaction_token = $userBalanceModel->createTransactionToken ( $userId );
		$result = $userBalanceModel->save ();
		if (empty ( $result )) {
			return null;
		}
		return $userBalanceModel->toArray();
	}
	public static function addUserBalance($userId,$money, $sourceId,$type = "robot_buy", $ext = []) {
		$hasAdd = UserBalanceLog::where(['user_id'=>$userId,'source_type'=>$type,'money'=>$money, 'source_id' => $sourceId])->find();
		if(!empty($hasAdd)){
			return false;
		}
		UserBalance::where(['user_id' => $userId])->lock(true)->find();
		$result = static::where(['user_id'=>$userId])->exp('balance',"balance+{$money}")->update();
		if (!$result) {
			return false;
		}
		$userBalance = static::get(['user_id'=>$userId]);
		$userId = $userBalance->user_id;
		$balanceId = $userBalance->user_balance_id;
		$currentBalance = $userBalance->balance;
		//添加收入日志
		if(!UserBalanceLog::addUserBalanceLog ( $userId, $balanceId, $type,$sourceId, $money, $currentBalance )){
			return  false;
		}
		return $userBalance;
	}
	public static function getBalanceByUseId($userId) {
		$balance = static::get ( [
				'user_id' => $userId
		] );
		if (empty ( $balance )) {
			return null;
		}
		return $balance;
	}

    public static function getCurrentBalanceByUseId($userId) {
        $balance = static::where('user_id',$userId)->value('balance');
        if (empty ( $balance )) {
            return 0.00;
        }
        return $balance;
    }

	public function checkBalance($money) {

		$userId = $this->user_id;
        if($this->balance < self::MIN_WITHDRAW_MONEY){
            return false;
        }
		$log = UserBalanceLog::where(['user_id'=>$userId])
					->where('status' , 'in', [UserBalanceLog::$statusMaps['init'],UserBalanceLog::$statusMaps['success']])
					->order('user_balance_log_id desc')->find();
		if(empty($log)){
			return false;
		}
		if(number_format($log['current_balance'], 2, '.', '') < number_format($money, 2, '.', '')){
			//return false;
		}
		
		$incomeMoney = UserBalanceLog::getIncomeMoney($userId);
		$costMoney = UserBalanceLog::getCostMoney($userId);
		
		$costMoney = number_format($costMoney+$money ,2,'.','');
		if (number_format($incomeMoney,2,'.','') >= $costMoney && number_format($this->balance, 2, '.', '') >= number_format($money, 2, '.', '')) {
			return true;
		}
		return false;
	}
	private function createTransactionToken($user_id, $balance = 0) {
		return md5 ( $user_id . $balance );
	}

    /**
     * 获取用户账户金额
     * @param  int $userId 用户ID
     * @return float
     */
	public static function getBalanceAmount($userId)
	{
		$where = array(
			'user_id' => $userId
		);

		$res = static::field('balance')->where($where)->find();
		return !empty($res) ? $res->balance : 0;
	}
}